<template>
  <div class="content-box-full">
    <ContainerBox>
      <template #header>
        <el-form
          @keyup.enter.native="handleSearch"
          ref="formRef"
          :model="searchForm"
          label-width="auto"
          inline
        >
          <el-form-item label="消费等级编号:" prop="consumptionPeriodNo">
            <el-input v-model="searchForm.consumptionLevelNo" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="消费等级名称:" prop="consumptionPeriodName">
            <el-input
              v-model.number="searchForm.consumptionLevelName"
              type="text"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              v-permission="'hire:consumptionlevel:list'"
              v-prevent-reclick
              type="primary"
              @click="handleSearch"
              >查询</el-button
            >
            <el-button
              v-permission="'hire:consumptionlevel:save'"
              @click="handleAdd"
              v-prevent-reclick
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-table
          :data="tableData"
          :empty-text="isLoadingTable ? '加载中...' : '暂无数据'"
          class="table-box"
          height="100%"
          stripe
          fit
          border
          highlight-current-row
        >
          <el-table-column type="index" align="center" label="序号" width="100"></el-table-column>
          <el-table-column label="消费等级编号" align="center" min-width="100" prop="levelCode">
          </el-table-column>
          <el-table-column label="消费等级名称" align="center" min-width="100" prop="name">
          </el-table-column>
          <el-table-column label="一天最大次数" align="center" min-width="100" prop="dayNumber">
          </el-table-column>
          <el-table-column label="一天最大金额" align="center" min-width="100" prop="dayAmount">
          </el-table-column>
          <el-table-column label="每餐最大次数" align="center" min-width="100" prop="eveyNumber">
          </el-table-column>
          <el-table-column label="每餐最大金额" align="center" min-width="100" prop="everAmount">
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" min-width="120">
            <template #default="{ row }">
              <el-button v-permission="'hire:consumptionlevel:update'" @click="editRow(row)"
                >编辑</el-button
              >
              <el-button v-permission="'hire:consumptionlevel:delete'" @click="deleteRow(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <CommonPaging
          :total="tableTotal"
          :current-page="pageNum"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
        ></CommonPaging>
      </template>
    </ContainerBox>
    <el-dialog
      lock-scroll
      top="10vh"
      class="common-el-dialog"
      v-model="showDialog"
      :title="dialogType === 'add' ? '新增' : '编辑'"
      width="600"
      @close="handleClose"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRules"
        label-width="120px"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="消费等级编号:" prop="consumptionLevelNo">
              <el-input
                :disabled="!isAdd"
                v-model="dataForm.consumptionLevelNo"
                type="text"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消费等级名称:" prop="consumptionLevelName">
              <el-input v-model="dataForm.consumptionLevelName" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一天最大次数:" prop="maxNumberDay">
              <el-input v-model.number="dataForm.maxNumberDay" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一天最大金额:" prop="maxPriceDay">
              <el-input v-model.number="dataForm.maxPriceDay" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="每餐最大次数:" prop="maxNumberMeal">
              <el-input v-model.number="dataForm.maxNumberMeal" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每餐最大金额:" prop="maxPriceMeal">
              <el-input v-model.number="dataForm.maxPriceMeal" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" v-prevent-reclick @click="handleFormSubmit"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import ContainerBox from '@/components/base/ContainerBox.vue'
import { ref, onMounted, computed } from 'vue'
import CommonPaging from '@/components/base/CommonPaging.vue'
import consumptionLevelApi from '@/api/consumptionLevelApi.js'
import message from '@/utils/elMessage.js'

onMounted(() => {
  fetchList()
})
const searchForm = ref({
  consumptionLevelNo: '', //消费等级编号
  consumptionLevelName: '', //消费等级名称
})
const pageNum = ref(1)
const pageSize = ref(10)

//查询
function handleSearch() {
  handleCurrentChange(1)
}

function fetchList() {
  isLoadingTable.value = true
  tableData.value = []
  const params = {
    page: pageNum.value,
    limit: pageSize.value,
    levelCode: searchForm.value.consumptionLevelNo,
    name: searchForm.value.consumptionLevelName,
  }
  consumptionLevelApi
    .fetchList(params)
    .then((res) => {
      if (res.code === 0) {
        const data = res.page || {}
        tableTotal.value = data.totalCount || 0
        tableData.value = data.list || []
      } else {
        message.warning(res.msg)
      }
    })
    .finally(() => {
      isLoadingTable.value = false
    })
}

// 列表数据
const isLoadingTable = ref(false)
const tableData = ref([])
const tableTotal = ref(0)

function editRow(row) {
  consumptionLevelApi.check(row.id).then((res) => {
    if (res.code === 0) {
      const { id, levelCode, name, dayNumber, dayAmount, eveyNumber, everAmount } =
        res.consumptionLevel || {}
      dataForm.value.id = id
      dataForm.value.consumptionLevelNo = levelCode
      dataForm.value.consumptionLevelName = name
      dataForm.value.maxNumberDay = dayNumber
      dataForm.value.maxPriceDay = dayAmount
      dataForm.value.maxNumberMeal = eveyNumber
      dataForm.value.maxPriceMeal = everAmount
      dialogType.value = 'edit'
      showDialog.value = true
    } else {
      message.warning(res.msg)
    }
  })
}

function deleteRow(row) {
  if (row.id) {
    message.confirm('您是否确定要删除该消费等级?', '提示').then(() => {
      consumptionLevelApi
        .delete([row.levelCode])
        .then((res) => {
          if (res.code === 0) {
            message.success(res.msg)
            fetchList()
          } else {
            message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.error(error.messages)
        })
    })
  }
}

function handleCurrentChange(val) {
  pageNum.value = val
  fetchList()
}

function handleSizeChange(val) {
  pageNum.value = 1
  pageSize.value = val
  fetchList()
}

// 新增食堂相关
const showDialog = ref(false)
const dialogType = ref('add')
const dataFormRef = ref(null)
//是否是新增操作
const isAdd = computed(() => dialogType.value === 'add')
const dataForm = ref({
  id: undefined, //编辑使用
  consumptionLevelNo: '', //消费等级编号
  consumptionLevelName: '', //消费等级名称
  maxNumberDay: '', //一天最大次数
  maxPriceDay: '', //一天最大金额
  maxNumberMeal: '', //每餐最大次数
  maxPriceMeal: '', //每餐最大金额
})
const dataRules = ref({
  consumptionLevelNo: [
    { required: true, message: '消费等级编号不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '消费等级编号不可以为空',
      trigger: 'change',
    },
  ],
  consumptionLevelName: [
    { required: true, message: '消费等级名称不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '消费等级名称不可以为空',
      trigger: 'change',
    },
  ],
  maxNumberDay: [
    { required: true, message: '一天最大次数不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '一天最大次数不可以为空',
      trigger: 'change',
    },
  ],
  maxPriceDay: [
    { required: true, message: '一天最大金额不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '一天最大金额不可以为空',
      trigger: 'change',
    },
  ],
  maxNumberMeal: [
    { required: true, message: '每餐最大次数不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '每餐最大次数不可以为空',
      trigger: 'change',
    },
  ],
  maxPriceMeal: [
    { required: true, message: '每餐最大金额不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '每餐最大金额不可以为空',
      trigger: 'change',
    },
  ],
})

//新增
function handleAdd() {
  dialogType.value = 'add'
  showDialog.value = true
}

function handleClose() {
  dataFormRef.value.resetFields()
}

function handleFormSubmit() {
  dataFormRef.value.validate((bool) => {
    if (bool) {
      const params = {
        id: isAdd.value ? undefined : dataForm.value.id,
        levelCode: dataForm.value.consumptionLevelNo,
        name: dataForm.value.consumptionLevelName,
        dayNumber: dataForm.value.maxNumberDay,
        dayAmount: dataForm.value.maxPriceDay,
        eveyNumber: dataForm.value.maxNumberMeal,
        everAmount: dataForm.value.maxPriceMeal,
      }
      const fetchApi = isAdd.value ? consumptionLevelApi.save : consumptionLevelApi.update
      fetchApi(params).then((res) => {
        if (res.code === 0) {
          isAdd.value ? handleCurrentChange(1) : fetchList()
          showDialog.value = false
        } else {
          message.warning(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped lang="scss"></style>
